let app = getApp()
import {
  tx_map
} from "../../utils/tx_map"
import {
  imageUrl
} from "../../utils/imageutil"
import {
  is_auth,
  rpxToPx,
  Precedence
} from "../../utils/util"
import {
  show_withdrawal
} from "../../utils/withdrawal"
import {
  title_name
} from "../../utils/api"
Page({
  data: {
    titleBarHeight: app.globalData.titleBarHeight,
    titleBarUsableWidth: app.globalData.titleBarUsableWidth - rpxToPx(64),
    statusBarHeight: app.globalData.statusBarHeight,
    barUsableHeight: app.globalData.barUsableHeight,
    barUsableTop: app.globalData.barUsableTop,
    barUsableBottom: app.globalData.barUsableBottom,
    rpx_20: rpxToPx(20),
    num: getApp().globalData.unreadCount,
    homets_info: null,
    is_user_know: false,
    is_user_all: false,
    is_withdrawal: false,
    withdrawal_obj: null,
    is_workRenew: false,
    workRenew_id: '',
    workRenew_list: [],
    title_name,
    longitude: '',
    latitude: '',
    city: '深圳市',
    remove_city: true,
    imageUrl,
    smbox: [{
      title: '品质保障 服务无忧',
      id: 1,
      icon: 11
    }, {
      title: '48小时专业培训',
      id: 2,
      icon: 22
    }, {
      title: '标准定价 售后无忧',
      id: 3,
      icon: 33
    }],
    mapH: 0,
    recommendedcurr: 2,
    recommendPage: 1,
    recommendFlag: true,
    recommendList: [],
    longitude: '',
    latitude: '',
    house_num: 0,
    store_num: 0,
    h5_height: app.globalData.Tabheight,

    navs: [],
    swiperCurrent: 0,

    fuwu_count: 0,
    order_count: 0,
    user_count: 0,
    work_count: 0,
    good_count: 0,
    house_count: 0,
    xianshang_count: 0,
    xianxia_count: 0,
    all: 0,

    id_number: wx.getStorageSync('userInfo').id_number,
    coupon_price: 0,

    tc_list: [],
    tc_flag: true,
    tc_page: 1,

    tc_and_card: [],
    bgImg: '/index/Slice1433_1.png',
    nav_id: 1,
    new_class_list: [
      imageUrl + '/index/Slice1292.png', imageUrl + '/index/Slice1300.png', imageUrl + '/index/Slice1306.png'
    ],
    page_nav: 1,
    list_nav: [],
    flag_nav: true,
    navcurr: 1,
    navlist: [{
        title: '全国',
        id: 1
      }, {
        title: '同城',
        id: 2,
      }, {
        title: '附近',
        id: 3
      },

    ],

  },

  onLoad(options) {

    wx.removeStorageSync('xieyiImageArr')
    wx.removeStorageSync('wailian_src')

    this.mapCtx = wx.createMapContext('mapId')
    this.getLogin();

    this.getnav();
    this.get_num();
    this.get_tc()
    this.getList()
    if (wx.getStorageSync('share_partner_name')) {
      this.setData({
        title: wx.getStorageSync('share_partner_name')
      })
    }
    wx.$TUIKit.on(wx.$TUIKitEvent.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated);

    if (wx.getStorageSync('share_partner_name')) {
      this.setData({
        title: wx.getStorageSync('share_partner_name')
      })
    }
    if (app.globalData.isIphoneX) {
      this.setData({
        mapH: app.globalData.windowHeight - rpxToPx(742 + 68)
      })
    } else {
      this.setData({
        mapH: app.globalData.windowHeight - rpxToPx(742)
      })
    }

  },
  //选阿姨和选套餐的点击事件
  to_aunt(e) { //家政员详情
    wx.navigateTo({
      url: '../aunt/index?uid=' + e.currentTarget.dataset.id + '&type=1',
    })
  },
  to_store(e) {
    wx.navigateTo({
      url: '../housekeeping/index?store_id=' + e.currentTarget.dataset.store_id,
    })
  },
  to_select(e) {

    let id = e.currentTarget.dataset.id
    if (id == 1) {
      this.setData({
        bgImg: '/index/Slice1433_1.png',
        nav_id: id,
        
        navcurr: 1
      })
      this.getList()
    } else {
      this.setData({
        bgImg: '/index/Slice1433_2.png',
        nav_id: id,
        navcurr: 1
      })
      this.get_tc()
    }
    console.log(this.data.nav_id, id, 'eeet');
  },
  changernavcurr(e) { //订单顶部状态切换
    if (this.data.nav_id == 1) {
      this.setData({
        navcurr: e.currentTarget.dataset.id,
        nav_list_type: 0,

        page_nav: 1,
        list_nav: [],
        flag_nav: true
      })
      this.getList()
    } else {
      this.setData({
        navcurr: e.currentTarget.dataset.id,
        nav_list_type: 0,
        tc_and_card:[],
        tc_page: 1,
        tc_list: [],
        tc_flag: true
      })
      this.get_tc()
    }

  },
  scrolltolower() {
    this.getList();
  },
  refresherrefresh() {
    this.setData({
      topflag: true,
      page_nav: 1,
      list_nav: [],
      flag_nav: true
    })
    this.getList();

  },
  scrolltolower2() {
    this.get_tc();
  },
  refresherrefresh() {
    this.setData({
      topflag: true,
      tc_page: 1,
      tc_list: [],
      tc_and_card:[],
      tc_flag: true
    })
    this.get_tc()

  },
  getList() {
    let city = ''
    if (this.data.navcurr == 2) {
      city = this.data.city
    } else {
      city = ""
    }
    getApp().globalData.post({
      url: "/api/applet.oyc/home_ay_list",
      data: {
        type: this.data.navcurr,
        cs: city,
        page: this.data.page_nav,
        services: this.data.services, //是否住家
        home: this.data.home //服务内容
      }
    }, true).then(res => {
      wx.stopPullDownRefresh();
      this.setData({
        typescurr: -1
      })
      if (res.data.data.length == 0) {
        this.setData({
          flag_nav: false
        })
      } else {
        let arr = this.data.list_nav.concat(res.data.data);
        this.setData({
          list_nav: arr,
          page_nav: this.data.page_nav + 1
        })
      }
    })
  },
  onConversationListUpdated() {
    this.setData({
      num: getApp().globalData.unreadCount
    })
  },
  handlePX() {
    wx.navigateTo({
      url: './train',
    })
  },
  onShow() {
    if (wx.getStorageSync('city')) {
      this.setData({
        city: wx.getStorageSync('city'),
        remove_city: false,
      })

      getApp().globalData.posts('/index.php/api/ouyoung/addresscontroller/citychange', {
        city: this.data.city,

      }).then(res => {
        if (res.data.code == 1) {
          let data = res.data.data
          this.setData({
            longitude: Number(data.lng),
            latitude: Number(data.lat),
          })

          this.reverse_geocoding(this.data.latitude, this.data.longitude)
        } else {
          let userInfo = wx.getStorageSync('userInfo')
          this.setData({
            longitude: Number(userInfo.lng),
            latitude: Number(userInfo.lat),
          })
          this.reverse_geocoding(this.data.latitude, this.data.longitude)
        }
      })
    } else {
      this.setData({
        remove_city: true
      })
      this.getCity();
    }
    this.setData({
      num: app.globalData.unreadCount,
      id_number: wx.getStorageSync('userInfo').id_number,
      coupon_price: wx.getStorageSync('userInfo').coupon_price
    })
    if (app.globalData.pop_num == 0) {
      app.globalData.pop_num = 1;
      this.setData({
        is_user_know: false,
        // is_user_all: true,
      })
      this.homets()
      // Precedence().then(type => {
      //   if (type == 3) {
      //     show_withdrawal(2).catch((obj) => {
      //       if (obj.step == 1) {
      //         app.globalData.pop_num = 0;
      //       }
      //       this.setData({
      //         is_user_know: false,
      //         is_withdrawal: true,
      //         withdrawal_obj: obj
      //       })
      //     })
      //   } else {
      //     this.workRenew()
      //   }
      // })
      this.getOrder() //授权接受订单信息
    }
  },

  get_num() {
    getApp().globalData.posts('/api/app/user/sorting/ouyoung_api/bitdata').then(res => {
      this.setData({
        ...res.data.data
      })

      let rpx62 = rpxToPx(62)

      let context = wx.createContext();
      let array = [this.data.xianshang_count, this.data.house_count, this.data.user_count];
      let colors = ["#31569F", "#FFB100", "#F0602B"];
      let total = 0;
      for (let index = 0; index < array.length; index++) {
        total += array[index];
      }
      let point = {
        x: rpx62,
        y: rpx62
      };
      let radius = rpx62;
      let pi = 2 * Math.PI;
      console.log(pi)
      /*  循环遍历所有的pie */
      for (let i = 0; i < array.length; i++) {
        context.beginPath();
        //    起点弧度
        let start = 0;
        if (i > 0) {
          //      计算开始弧度是前几项的总和，即从之前的基础的上继续作画
          for (let j = 0; j < i; j++) {
            start += array[j] / total * pi;
          }
        }
        console.log("i:" + i);
        console.log("start:" + start);
        //   1.先做第一个pie
        //    2.画一条弧，并填充成三角饼pie，前2个参数确定圆心，第3参数为半径，第4参数起始旋转弧度数，第5参数本次扫过的弧度数，第6个参数为时针方向-false为顺时针
        context.arc(point.x, point.y, radius, start, start + (array[i] / total * pi), false);
        //   3.连线回圆心
        context.lineTo(point.x, point.y);
        //   4.填充样式
        context.setFillStyle(colors[i]);
        //   5.填充动作
        context.fill();
        context.closePath();
      }


      wx.drawCanvas({
        canvasId: 'canvas2',
        actions: context.getActions()
      });
    })
  },

  homets() {
    getApp().globalData.post({
      url: '/api/ouyoung/homets',
    }, true).then(res => {
      if (res.data.code == 1) {
        this.setData({
          homets_info: res.data.data,
          is_user_all: true,
        })
      }
    })
  },


  // onReachBottom() {
  //   console.log("触底了吗");
  //   this.get_tc()
  // },

  get_tc() {
    if (!this.data.tc_flag) {
      return false
    }
    this.setData({
      tc_flag: false
    })
    getApp().globalData.post({
      url: '/api/applet.oyc/fx_combo_list',
      data: {
        pagesize: 10,
        page: this.data.tc_page,
        type: this.data.navcurr,
        cs:this.data.navcurr==2?this.data.city:'',
        // url_type: 2,
      }
    }, true).then(res => {
      wx.stopPullDownRefresh();
      if (res.data.data.length == 0) {
        this.setData({
          tc_flag: false
        })
      } else {
        let tc_and_card = this.data.tc_and_card
        let arr = this.data.tc_list.concat(res.data.data);
        tc_and_card.push([...res.data.data])
        this.setData({
          tc_list: arr,
          tc_and_card,
          tc_flag: true,
          tc_page: this.data.tc_page + 1
        })
      }
    })
  },

  to_projects(e) {
    if (!is_auth(true)) {
      return
    }
    wx.navigateTo({
      url: '../all/make?good_id=' + e.currentTarget.dataset.id,
    })
  },

  to_dan() {
    if (!is_auth(true)) {
      return
    }
    wx.navigateTo({
      url: '/pages/news/news?nav_curr=3'
    })
  },

  openmap(e) {
    wx.navigateTo({
      url: '../housekeeping/index?store_id=' + e.currentTarget.dataset.store_id,
    })
  },

  to_withdrawal() {
    wx.navigateToMiniProgram({
      ...this.data.withdrawal_obj.obj
    })
  },

  change_user_know() {
    this.setData({
      is_user_know: false
    })
  },
  change_is_user_all() {
    this.setData({
      is_user_all: false
    })
  },
  change_is_user_all_homets_info() {
    this.setData({
      is_user_all: false
    })
    if (this.data.homets_info.url) {
      wx.setStorageSync('xieyiImageArr', this.data.homets_info.img_list)
      wx.setStorageSync('wailian_src', this.data.homets_info.src)
      wx.navigateTo({
        url: this.data.homets_info.url
      })
    }
  },
  change_is_workRenew() {
    this.setData({
      is_workRenew: false
    })
  },
  change_is_withdrawal() {
    app.globalData.pop_num = 1;
    this.setData({
      is_withdrawal: false
    })
  },
  to_plan() {
    this.change_is_workRenew()
    wx.navigateTo({
      url: '/pages/matron/plan?wid=' + this.data.workRenew_id,
    })
  },

  workRenew() {
    getApp().globalData.posts('/index.php/api/app/user/sorting/ouyoung_api/workRenew').then(res => {
      if (res.data.code == 1) {
        this.setData({
          is_user_know: false,
          is_workRenew: true,
          workRenew_list: res.data.data.text,
          workRenew_id: res.data.data.work.id
        })
      }
    })
  },

  getOrder() {
    wx.showModal({
      title: '提示',
      content: '是否允许接收订单消息通知?',
      success(res) {
        if (res.confirm) {
          wx.requestSubscribeMessage({
            tmplIds: ['EGHbDpl4RBrV0U_2MP9bxyqnkZ6gqFZYp3-c-7nqIy0', 'Wbq0s71nl-7t0dwrlLLmJSoIB0tdmVhDkqE77lmv2uQ', 'gALuHxhkWQ-_N4hZAsDcRWbjSxoV34B52Sx0KwpkdKE']
          })
        }
      }
    })
  },
  getLogin() {
    getApp().globalData.posts('/api/auth/login', {
      "openid": wx.getStorageSync('jz_getOpenId')
    }).then(res => {
      wx.setStorageSync('ay_token', res.data.data.token)
    })
  },

  getmy_address() {
    this.mapCtx.moveToLocation({
      complete: (res) => {
        if (res.errMsg == "moveToMapLocation:ok") {
          this.setData({
            remove_city: true
          })
          this.getCity()
        } else if (res.errMsg == "moveToMapLocation:fail") {
          getApp().showModal('是否打开设置授权位置信息？', true).then(() => {
            wx.openSetting({
              success: (s) => {
                if (s.authSetting['scope.userLocation']) {
                  this.getmy_address()
                }
              }
            });
          })
        }
      }
    })
  },

  getCity() {
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setData({
          longitude: Number(res.longitude),
          latitude: Number(res.latitude),
        })
        getApp().globalData.posts('/index.php/api/ouyoung/addresscontroller/citychange', {
          city: this.data.city,
          lat: Number(res.latitude),
          lng: Number(res.longitude),
        }).then(res => {
          if (res.data.code == 1) {
            let data = res.data.data
            this.setData({
              longitude: Number(data.lng),
              latitude: Number(data.lat),
            })
            this.reverse_geocoding(this.data.latitude, this.data.longitude)
          } else {
            let userInfo = wx.getStorageSync('userInfo')
            this.setData({
              longitude: Number(userInfo.lng),
              latitude: Number(userInfo.lat),
            })
            this.reverse_geocoding(this.data.latitude, this.data.longitude)
          }
        })
        this.reverse_geocoding(this.data.latitude, this.data.longitude)
      },
      fail: (e) => {
        getApp().showModal('是否打开设置授权位置信息？', true).then(() => {
          wx.openSetting({
            success: (s) => {
              if (s.authSetting['scope.userLocation']) {
                this.getCity()
              }
            }
          });
        })
      }
    })
  },
  reverse_geocoding(latitude, longitude) {

    getApp().reverse_geocoding(latitude, longitude).then(result => {
      console.log("我是城市2");
      let addressComponent = result.addressComponent;
      // this.setData({
      //   city: addressComponent.city,
      // });
      if (this.data.remove_city) {
        wx.removeStorageSync('city')
      } else {
        wx.setStorageSync('city', this.data.city)
      }
      this.updateLatAndLng(this.data.latitude, this.data.longitude, addressComponent.adcode, addressComponent.province, addressComponent.city, addressComponent.district, addressComponent.street).then(() => {

        this.setData({
          recommendFlag: true
        })
        this.housekeeperList()

      })
    })
  },
  updateLatAndLng(lat, lng, area_code, province, city, district, town) {
    return new Promise((reslove, reject) => {
      let obj = {}
      if (this.data.remove_city) {
        obj = {
          province,
          city,
          district,
          town
        }
      }
      this.setData({
        tc_flag: true,
        tc_page: 1,
        tc_list: [],
        tc_and_card: []
      })
      this.get_tc()
      reslove()
    })
  },

  to_yuan() {
    wx.navigateTo({
      url: '/pages/webview/web?url=https://xfjz.xfyh4k5.com/metaverse/index.html',
    })
  },
  to_city() {
    if (!is_auth(true)) {
      return false
    }
    wx.navigateTo({
      url: './switchcity?city=' + this.data.city,
    })
  },
  to_search() {
    wx.navigateTo({
      url: './search',
    })
  },
  to_urls(e) {
    console.log(e, "xixi");
    wx.navigateTo({
      url: e.currentTarget.dataset.url,
    })
  },
  to_union() {
    wx.navigateTo({
      url: '/pages/union/new_union',
    })
  },
  to_url(e) {
    if (!is_auth(true)) {
      return
    }
    if (e.currentTarget.dataset.src) {
      wx.navigateTo({
        url: e.currentTarget.dataset.src
      })
    } else {
      return
      wx.showToast({
        title: '该功能正在开发中！',
        icon: 'none'
      })
    }
  },

  onShareAppMessage() {
    let url = '/pages/index/index'
    url = encodeURIComponent(url)
    return {
      path: '/pages/index/blank?to_id=' + wx.getStorageSync('userInfo').id + '&tourl=' + url,
      title: this.data.title_name,
    }
  },

  housekeeperList() {
    // 家政员列表
    if (!this.data.recommendFlag) {
      return false
    }
    this.setData({
      recommendFlag: false
    })
    app.globalData.posts('/index.php/api/app/user/fjay').then(res => {
      wx.stopPullDownRefresh();
      if (res.data.data.list.length == 0) {
        this.setData({
          recommendFlag: false
        })
      } else {
        let arr = this.data.recommendList.concat(res.data.data.data);
        this.setData({
          house_num: res.data.data.house_num,
          store_num: res.data.data.store_num,
          recommendList: arr,
          recommendFlag: true,
          recommendPage: this.data.recommendPage + 1
        })
        this.bindEvent()
      }
    })
  },

  getRecommend() {
    // 套餐列表
    if (!this.data.recommendFlag) {
      return false
    }
    this.setData({
      recommendFlag: false
    })
    let data = {
      do: 'Recommend',
      uid: wx.getStorageSync('userInfo').id,
      page: this.data.recommendPage,
      type: this.data.recommendedcurr,
      pagesize: 10,
      longitude: this.data.longitude,
      latitude: this.data.latitude,
      long: this.data.longitude,
      lat: this.data.latitude,
    }
    app.globalData.post({
      data
    }).then(res => {
      wx.stopPullDownRefresh();
      if (res.data.data.length == 0 || !res.data.data) {
        this.setData({
          recommendFlag: false
        })
      } else {
        let arr = this.data.recommendList.concat(res.data.data);
        this.setData({
          recommendList: arr,
          recommendFlag: true,
          recommendPage: this.data.recommendPage + 1
        })
        // this.bindEvent()
      }
    })
  },

  bindEvent() {
    this.mapCtx.initMarkerCluster({
      enableDefaultStyle: false,
      zoomOnClick: true,
      gridSize: 60,
      complete(res) {
        console.log('initMarkerCluster', res)
      }
    })
    // this.addMarkers()
    this.addMarkers_aunt()
  },
  addMarkers() {
    const marker = {
      width: 50,
      height: 50,
    }

    const markers = []
    this.data.recommendList.forEach((p, i) => {
      const newMarker = Object.assign(marker, {})
      newMarker.id = i + 1;
      newMarker.iconPath = p.logo;
      newMarker.latitude = p.latitude;
      newMarker.longitude = p.longitude;
      markers.push(newMarker)

      this.mapCtx.addMarkers({
        markers,
        clear: true,
        complete(res) {
          console.log('addMarkers', res)
        }
      })
    })
  },
  addMarkers_aunt() {
    const marker = {
      width: 30,
      height: 34,
      borderRadius: 10,
      joinCluster: true,
      label: {
        borderRadius: 10,
        borderWidth: 0,
        borderColor: '#ffffff',
        width: 30,
        height: 34,
        anchorX: -10,
        anchorY: -20
      }
    }
    const markers = []
    this.data.recommendList.forEach((p, i) => {
      const newMarker = Object.assign(marker, {})
      if (p.latitude == 0) {
        return
      }
      newMarker.id = i + 1;
      if (p.usertype == 1) {
        newMarker.iconPath = 'https://cyxf.xfyh4k5.com/jiazheng/image/index/index_fw_logo.png';
        newMarker.latitude = p.lat;
        newMarker.longitude = p.lng;
        newMarker.callout = {
          content: p.user_nickname,
          color: '#333333',
          fontSize: '12',
          bgColor: "#ffffff",
          padding: '5',
          borderRadius: '6',
          borderWidth: 0,
          textAlign: 'center',
          display: 'ALWAYS'
        };
      } else if (p.usertype == 2) {
        newMarker.iconPath = 'https://cyxf.xfyh4k5.com/jiazheng/image/index/index_gs_logo.png';
        newMarker.latitude = p.latitude;
        newMarker.longitude = p.longitude;
        newMarker.callout = {
          content: p.name,
          color: '#333333',
          fontSize: '12',
          bgColor: "#ffffff",
          padding: '10',
          borderRadius: '6',
          borderWidth: 0,
          textAlign: 'center',
          display: 'ALWAYS'
        };
      }

      markers.push(newMarker)

      this.mapCtx.addMarkers({
        markers,
        clear: false,
        complete(res) {
          // console.log('addMarkers', res)
        }
      })
    })
  },
  onMarkerTap(e) {
    console.log('@@ markertap', e)
  },
  onCalloutTap(e) {
    console.log('@@ onCalloutTap', e)
  },
  onLabelTap(e) {
    console.log('@@ labletap', e)
  },
  change_location(e) {
    console.log(e)
  },

  contact() {
    getApp().contact()
  },


  changeSwiper(e) {
    this.setData({
      swiperCurrent: e.detail.current
    })
  },
  getnav() {
    app.globalData.post({
      data: {
        do: 'TypeAd'
      }
    }).then(res => {
      this.setData({
        navbox: res.data
      })
      let a = [];
      for (let e = 0, s = res.data.length; e < s; e += 8) {
        a.push(res.data.slice(e, e + 8));
      }
      this.setData({
        navs: a
      })
    })
  },

  to_yyz() {

    wx.navigateTo({
      url: '/order/news',
    })
  },

  to_ai() {
    let url = encodeURIComponent('https://ai.xfyh4k5.com/')
    wx.navigateTo({
      url: '/pages/webview/web?url=' + url,
    })
  },

  to_cct() {
    wx.navigateTo({
      url: './aunt?city=' + this.data.city
    })
  },

  to_ykz() {
    wx.navigateTo({
      url: './search'
    })
  },

  look_v() {
    if (wx.getStorageSync('userInfo').id == '4672' || wx.getStorageSync('userInfo').phonenumber == '13413014311') {
      const miniProgram = wx.getAccountInfoSync().miniProgram;
      getApp().showModal(miniProgram.envVersion + miniProgram.version).then(() => {
        // getApp().i_bx(24)
        getApp().globalData.posts('/api/app/laundryclub/sorting/oyaction/test').then(res => {
          let pay_info = res.data.data
          wx.requestPayment({
            ...pay_info
          })
        })
      })
    }
  },


})